/*
* Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* $Id: tabwidget.cpp 329 2009-03-01 13:45:29Z vjousse $
*/

#include "tabwidget.h"
#include <QShortcut>

TabWidget::TabWidget(QWidget* parent)
	: QTabWidget(parent)
{
	connect(this, SIGNAL(currentChanged(int)), SLOT(onCurrentChanged(int)));

    QShortcut* shortcut = new QShortcut(QKeySequence(tr("Alt+Left")), this);
    connect(shortcut, SIGNAL(activated()), this, SLOT(moveToPrevTab()));

    shortcut = new QShortcut(QKeySequence(tr("Alt+Right")), this);
    connect(shortcut, SIGNAL(activated()), this, SLOT(moveToNextTab()));
}

QWidget* TabWidget::container()
{
    return this;
}

void TabWidget::addView(MessageView* view)
{
	int index = addTab(view, view->windowTitle());
    d.tabIndexes.insert(view, index);
	setCurrentIndex(index);
}

void TabWidget::removeView(MessageView* view)
{
	Q_ASSERT_X(false, "TabWidget::removeView", "TODO");
    d.tabIndexes.remove(view);
}

QList<MessageView*> TabWidget::takeAllViews()
{
	QList<MessageView*> views;
	while (count() > 0)
	{
		views += static_cast<MessageView*>(widget(0));
		removeTab(0);
	}
	return views;
}

MessageView* TabWidget::currentView()
{
    return static_cast<MessageView*>(currentWidget());
}

void TabWidget::setCurrentView(MessageView* view)
{
	if (!d.tabIndexes.contains(view))
	{
        qWarning("TabWidget::setCurrentView unknown view?");
        return;
	}
    setCurrentIndex(d.tabIndexes.value(view));
}

void TabWidget::onCurrentChanged(int index)
{
	if (MessageView* view = static_cast<MessageView*>(widget(index)))
        emit currentViewChanged(view);
}

void TabWidget::closeTab(int index)
{
	removeTab(index);
}

void TabWidget::moveToNextTab()
{
    int index = currentIndex();
    if (++index >= count())
        index = 0;
    setCurrentIndex(index);
}

void TabWidget::moveToPrevTab()
{
    int index = currentIndex();
    if (--index < 0)
        index = count() - 1;
    setCurrentIndex(index);
}
